﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;

public class ProjectFactory
{
    private static ProjectFactory instance;
    private MysqlConnector connector;

	private ProjectFactory()
    {
        connector = MysqlConnector.getInstance();
	}

    public static ProjectFactory getInstance()
    {
        if (instance == null)
        {
            instance = new ProjectFactory();
        }
        return instance;
    }

    public List<Project> getProjectsForUser(int userId)
    {
        String query = "SELECT * FROM project JOIN user_2_project u2p ON u2p.project = project.id WHERE u2p.user = " + userId;
        MySqlDataReader dr = connector.Select(query);
        List<Project> projects = new List<Project>();

        while (dr.Read())
        {
            Project newProject = new Project();
            newProject.name = dr.GetString(1);
            newProject.category = dr.GetString(2);
            newProject.description = dr.GetString(3);
            newProject.created = dr.GetDateTime(4);
            newProject.createdBy = UserFactory.getInstance().getUserById(dr.GetInt32(5));

            projects.Add(newProject);
        }
        return projects;
    }

    public void createProject(String name, String category, String description, int userId)
    {

        String query = "INSERT INTO project (name, category, description, createdBy) VALUES('" +
            connector.cleanParam(name) + "', '" +
            connector.cleanParam(category) + "', '" +
            connector.cleanParam(description) + "', " +
            userId + ");";

        connector.Insert(query);
    }
}
